from flask import current_app
from sqlalchemy import func

from cache.statistic import UserArticleCountStorage, UserFollowingsCountStorage, UserFansCountStorage
from models import db
from models.news import Article


def __fix_statistic(cls):
    try:
        # 先到mysql中查询数据
        ret = cls.db_query()
        # 校正redis数据
        cls.reset(ret)
    except BaseException as e:
        current_app.logger.error(e)
        raise e


def fix_statistic(app):
    """修正统计数据"""

    with app.app_context():

        # 校正所有用户的作品数量
        __fix_statistic(UserArticleCountStorage)

        # 校正所有用户的关注数量
        __fix_statistic(UserFollowingsCountStorage)

        # 校正所有用户的分析数量
        __fix_statistic(UserFansCountStorage)